package org.noote.roby.monitor;

import org.noote.libs.roby.comm.IPCommandEvents;
import org.noote.libs.roby.comm.IPCommandProtocol;
import org.noote.libs.tcpip.IPClient;

import android.util.Log;

public class IPProtocole {
	private static final String LOG_TAG = "IPProtocole";	

	// TODO : verifier que ca fonctionne :)
	synchronized public ResponseHello sendHelloToServer(String sServerIP, int iPort, final String sControllerName, final String sControllerVersion) {
		final ResponseHello mRet = new ResponseHello();
		Log.d(LOG_TAG, "Try to send a 'one shot' hello message to " + sServerIP + ":" + String.valueOf(iPort));
		
		IPCommandEvents mEvents = new IPCommandEvents()
		{
			@Override
			public void onConnected() {
				_thread.sendMessage(IPCommandProtocol.sendHello(sControllerName, sControllerVersion));
			}
			@Override
			public void onDisconnected() {
				_thread.close();
				IPProtocole.this.notify();
			}
			@Override
			public void onError(String sError) {
				_thread.close();
				IPProtocole.this.notify();
			}
			@Override
			public void onHello(String sName, String sVersion) {
				if(sName.length()>0)
					mRet.sName = sName;
				if(sVersion.length()>0)
					mRet.sVersion = sVersion;
				
				_thread.sendMessage(IPCommandProtocol.sendQuit());
			}
		};
		
		IPClient _IPClient = new IPClient(mEvents);
		if(_IPClient.connect(sServerIP, iPort))
		{
			try {
				wait(); // wait for notify push
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			return mRet;
		}
		
		return null;
	}
}
